package com.ch.base.utils;

import com.ch.base.handler.SheetHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ooxml.util.SAXHelper;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * process file util
 * created in 2019-04-19 13:22
 **/
@Slf4j
public class FileUtil {

    /**
     * Verify that the file is not xlsx
     *
     * @param filename the file name
     * @return boolean
     */
    public static boolean isNotXlSX(String filename) {

        return !filename.matches("^.+\\.(xlsx)$");
    }

    public static List<Map<String, String>> processExcelOneSheet(MultipartFile file) throws Exception {

        log.info("start:read[" + file.getOriginalFilename() + "]");
        OPCPackage pkg = OPCPackage.open(file.getInputStream());
        XSSFReader reader = new XSSFReader(pkg);
        SharedStringsTable sst = reader.getSharedStringsTable();

        XMLReader parser = fetchSheetParser(sst);
        //normally it`s of the form rId# or rSheet#
        InputStream sheet = reader.getSheet("rId1");
        InputSource sheetSource = new InputSource(sheet);
        parser.parse(sheetSource);

        SheetHandler handler = (SheetHandler) parser.getContentHandler();
        List<Map<String, String>> data = handler.getData();
        data.removeIf(datum -> datum == null || datum.size() == 0);
        log.info("读取EXCEL[" + handler.getRowNum() + "]行数据");
        log.info("共读取有效数据[" + data.size() + "]条");
        sheet.close();
        log.info("end:read[" + file.getOriginalFilename() + "]");
        return data;
    }

    private static XMLReader fetchSheetParser(SharedStringsTable sst)
            throws ParserConfigurationException, SAXException {

        XMLReader parser = SAXHelper.newXMLReader();
        ContentHandler handler = new SheetHandler(sst);
        parser.setContentHandler(handler);
        return parser;
    }
}
